package com.yuyang.gulimalltestssoserver.controller;

import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author yu yang
 * @date 2023/1/27 -14:47
 */
@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @GetMapping("/userInfo")
    @ResponseBody
    public String info(@RequestParam("token")String token){
        return stringRedisTemplate.opsForValue().get(token);
    }
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false)String token){
        if (token != null){
            //已经登陆
            return "redirect:"+url+"?token="+token;
        }
        model.addAttribute("url",url);
        return "login";
    }
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username")String username,
                          @RequestParam("password")String password,
                          @RequestParam("url") String url, HttpServletResponse response){
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登陆成功保存用户信息
            String uuid = UUID.randomUUID().toString().replace("-","");
            stringRedisTemplate.opsForValue().set(uuid,username);
            //服务器留下登录痕迹
            response.addCookie(new Cookie("sso_token",uuid));
            //重定向到客户端，携带token
            return "redirect:"+url+"?token="+uuid;
        }else {
            return "login";
        }
    }
}
